package org.example.orders_learn.controller;


import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.orders_learn.common.Result;
import org.example.orders_learn.entity.Orders;
import org.example.orders_learn.enums.Events;
import org.example.orders_learn.enums.Status;
import org.example.orders_learn.service.OrdersService;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.web.bind.annotation.*;

/**
 * @author wuyunbin
 */
@RestController
@RequestMapping(value = "orders")
@Slf4j
public class OrdersController {
    @Resource
    private OrdersService ordersService;

    @Resource
    private StateMachine<Status, Events> stateMachine;

    @PostMapping("createOrders")
    public void addOrders(@RequestBody Orders orders) {
//        ordersService.addOrders(orders);
//        return Result.success();
//        不放入service，直接使用状态机
        Message<Events> message = MessageBuilder.withPayload(Events.CREATE).build();
        boolean event = stateMachine.sendEvent(message);
        log.info("下单{}",event);
        ordersService.save(orders);

    }

    @PutMapping("updateOrders")
    public Result updateOrders(@RequestBody Orders orders) {
        if ("1".equals(orders.getStatus())
                || "2".equals(orders.getStatus())
                || "3".equals(orders.getStatus())) {
            ordersService.updateById(orders);
            return Result.success();
        }else{
            return Result.error("订单状态错误");
        }
    }
}
